package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import org.apache.tomcat.jni.Lock;
import org.apache.tomcat.jni.Time;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CacheClient cacheClient;

    // 线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Override
    public Result queryShopById(Long id) {
        // // 缓存穿透
        // Shop shop = cacheClient.
        //         queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, id2->getById(id2), CACHE_SHOP_TTL, TimeUnit.MINUTES);

        // 缓存击穿 - 互斥锁
        // Shop shop = queryWithMutex(id);

        // 缓存击穿 - 逻辑过期
        Shop shop = cacheClient.
                queryWithLogicalExpire(CACHE_SHOP_KEY, LOCK_SHOP_KEY, id, Shop.class, this::getById, 20L, TimeUnit.SECONDS);

        if(shop == null){
            return Result.fail("店铺不存在!");
        }

        return Result.ok(shop);
    }

    // 缓存击穿 - 逻辑过期
    public Shop queryWithLogicalExpire(Long id){
        String shopKey = CACHE_SHOP_KEY + id;
        // 1. 从Redis查询商铺缓存
        String cacheShop = stringRedisTemplate.opsForValue().get(shopKey);
        // 2. 判断缓存是否命中
        if(StringUtils.isBlank(cacheShop)){
            // 3. 未命中, 返回空
            return null;
        }
        // 4. 命中, 取出商铺数据和过期时间
        RedisData redisData = JSON.parseObject(cacheShop, RedisData.class);
        JSONObject data = (JSONObject)redisData.getData();
        Shop shop = JSON.parseObject(data.toJSONString(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();


        // 5. 判断缓存是否过期
        if(expireTime.isAfter(LocalDateTime.now())){
            // 6. 未过期
            return shop;
        }
        // 7. 过期, 尝试获取互斥锁
        String lockKey = LOCK_SHOP_KEY+id;
        boolean isLock = tryLock(lockKey);
        if(isLock){
            // 8. 获取成功, 开启独立线程, 缓存数据
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    // 重建缓存
                    saveShopToRedis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    // 释放锁
                    unLock(lockKey);
                }
            });
        }
        // 9. 获取失败, 返回商铺信息
        return shop;
    }

    // 缓存击穿 - 互斥锁
    public Shop queryWithMutex(Long id){
        String shopKey = CACHE_SHOP_KEY + id;
        // 1. 从Redis查询商铺缓存
        String cacheShop = stringRedisTemplate.opsForValue().get(shopKey);
        // 2. 判断缓存是否命中
        if(StringUtils.isNotBlank(cacheShop)){
            // 3. 命中, 返回商铺信息
            Shop shop = JSON.parseObject(cacheShop, Shop.class);
            return shop;
        }
        // 缓存穿透: 判断是否是空对象, 健不存在的话需要去数据库查, 键存在但是是空对象则直接返回
        if(cacheShop != null){
            return null;
        }

        // 4. 未命中, 缓存重建
        // 4.1 尝试获取互斥锁

        String lockKey = LOCK_SHOP_KEY+id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockKey);
            // 4.2 判断是否获取成功
            if(!isLock){
                // 4.3 失败, 休眠并重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            // 4.4 获取锁, 根据id查询数据库
            shop = getById(id);
            // 5. 判断商铺是否存在
            if(shop == null){
                // 6. 缓存穿透, 缓存空对象
                stringRedisTemplate.opsForValue().set(shopKey, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            // 7. 存在, 将商铺数据写入Redis并返回
            stringRedisTemplate.opsForValue().set(shopKey, JSON.toJSONString(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 8. 释放锁
            unLock(lockKey);
        }

        // 9. 返回
        return shop;
    }

    // 缓存穿透
    public Shop queryWithPassThrough(Long id){
        String shopKey = CACHE_SHOP_KEY + id;
        // 1. 从Redis查询商铺缓存
        String cacheShop = stringRedisTemplate.opsForValue().get(shopKey);
        // 2. 判断缓存是否命中
        if(StringUtils.isNotBlank(cacheShop)){
            // 3. 命中, 返回商铺信息
            Shop shop = JSON.parseObject(cacheShop, Shop.class);
            return shop;
        }
        // 缓存穿透: 判断是否是空对象, 健不存在的话需要去数据库查, 键存在但是是空对象则直接返回
        if(cacheShop != null){
            return null;
        }
        // 4. 未命中, 根据id查询数据库
        Shop shop = getById(id);
        // 5. 判断商铺是否存在
        if(shop == null){
            // 6. 缓存穿透, 缓存空对象
            stringRedisTemplate.opsForValue().set(shopKey, "");
            stringRedisTemplate.expire(shopKey, CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        // 7. 存在, 将商铺数据写入Redis并返回
        stringRedisTemplate.opsForValue().set(shopKey, JSON.toJSONString(shop));
        stringRedisTemplate.expire(shopKey, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }

    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(flag);
    }

    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }

    public void saveShopToRedis(Long id, Long expireSeconds) throws InterruptedException {
        // 1. 查询商铺数据
        Shop shop = getById(id);
        // 1.1 模拟复杂查询
        Thread.sleep(200);
        // 2. 创建缓存数据
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        // 3. 将数据缓存导redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id, JSON.toJSONString(redisData));
    }

    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if(id == null){
            return Result.fail("店铺id不能为空!");
        }
        String shopKey = CACHE_SHOP_KEY + id;
        // 1. 修改数据库
        updateById(shop);
        // 2. 删除缓存
        stringRedisTemplate.delete(shopKey);
        // 3. 返回ok
        return Result.ok();
    }
}
